import { useState, useEffect } from 'react'
import './App.css'

// 定义任务组类型
interface TaskGroup {
  id: string
  name: string
  createTime: Date
}

// 定义任务状态类型
type TaskStatus = 'pending' | 'inProgress' | 'completed' | 'paused'

// 定义任务类型
interface Todo {
  id: string
  text: string
  completed: boolean
  createTime: Date
  groupId: string
  status: TaskStatus
  assignee?: string
  dueTime?: Date
  description?: string
}

// 定义过滤器类型
type FilterType = 'all' | 'active' | 'completed'

// 定义排序方向
type SortDirection = 'asc' | 'desc'

// 定义用户类型
interface User {
  username: string
  isGuest: boolean
}

function App() {
  // 状态定义
  const [todos, setTodos] = useState<Todo[]>([])
  const [selectedTodoIds, setSelectedTodoIds] = useState<string[]>([])
  const [statusFilter, setStatusFilter] = useState<TaskStatus | 'all'>('all')
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc')
  const [assigneeFilter, setAssigneeFilter] = useState<string>('')
  const [showSelectionOptions, setShowSelectionOptions] = useState(false)
  const [taskGroups, setTaskGroups] = useState<TaskGroup[]>([])
  const [currentGroupId, setCurrentGroupId] = useState<string>('default')
  const [inputText, setInputText] = useState('')
  const [filter, setFilter] = useState<FilterType>('all')
  const [isInputFocused, setIsInputFocused] = useState(false)
  const [showSidebar, setShowSidebar] = useState(true)
  const [showAddGroupModal, setShowAddGroupModal] = useState(false)
  const [newGroupName, setNewGroupName] = useState('')
  const [showAddTaskModal, setShowAddTaskModal] = useState(false)
  const [taskAssignee, setTaskAssignee] = useState('')
  const [taskDueTime, setTaskDueTime] = useState('')
  const [taskDescription, setTaskDescription] = useState('')
  const [showStatusDropdown, setShowStatusDropdown] = useState(false)
  
  // 用户相关状态
  const [user, setUser] = useState<User | null>(null)
  const [showLoginModal, setShowLoginModal] = useState(false)
  const [showRegisterModal, setShowRegisterModal] = useState(false)
  const [loginUsername, setLoginUsername] = useState('')
  const [loginPassword, setLoginPassword] = useState('')
  const [registerUsername, setRegisterUsername] = useState('')
  const [registerPassword, setRegisterPassword] = useState('')
  const [authError, setAuthError] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  // 生成随机游客用户名
  const generateGuestUsername = () => {
    const adjectives = ['快乐的', '友好的', '聪明的', '勇敢的', '可爱的', '活泼的', '安静的', '机智的'];
    const nouns = ['猫咪', '狗狗', '兔子', '熊猫', '狐狸', '老虎', '狮子', '大象'];
    const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
    const noun = nouns[Math.floor(Math.random() * nouns.length)];
    const num = Math.floor(Math.random() * 1000);
    return `${adj}${noun}${num}`;
  };

  // 用户登录
  const login = async () => {
    setIsLoading(true);
    setAuthError('');
    
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username: loginUsername, password: loginPassword }),
      });
      
      const result = await response.json();
      
      if (result.success) {
        // 设置用户信息
        setUser({ username: result.username, isGuest: false });
        
        // 加载用户数据
        if (result.data) {
          const { todos: userTodos, taskGroups: userGroups } = result.data;
          
          // 处理任务组数据
          if (userGroups && userGroups.length > 0) {
            try {
              const parsedGroups = userGroups.map((group: any) => ({
                ...group,
                createTime: new Date(group.createTime)
              }));
              setTaskGroups(parsedGroups);
            } catch (e) {
              console.error('解析用户任务组失败:', e);
            }
          }
          
          // 处理任务数据
          if (userTodos && userTodos.length > 0) {
            try {
              const parsedTodos = userTodos.map((todo: any) => ({
                ...todo,
                createTime: new Date(todo.createTime),
                groupId: todo.groupId || 'default'
              }));
              setTodos(parsedTodos);
            } catch (e) {
              console.error('解析用户任务失败:', e);
            }
          }
        }
        
        // 关闭登录模态框并清除表单
        setShowLoginModal(false);
        setLoginUsername('');
        setLoginPassword('');
        
        // 保存登录状态到localStorage
        localStorage.setItem('user', JSON.stringify({ username: result.username, isGuest: false }));
      } else {
        setAuthError(result.message || '登录失败');
      }
    } catch (error) {
      console.error('登录异常:', error);
      setAuthError('登录时发生错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 用户注册
  const register = async () => {
    setIsLoading(true);
    setAuthError('');
    
    try {
      // 准备游客数据（如果有的话）
      const guestData = user?.isGuest ? {
        todos,
        taskGroups
      } : undefined;
      
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          username: registerUsername, 
          password: registerPassword,
          guestData
        }),
      });
      
      const result = await response.json();
      
      if (result.success) {
        // 注册成功后自动登录
        setUser({ username: registerUsername, isGuest: false });
        
        // 关闭注册模态框并清除表单
        setShowRegisterModal(false);
        setRegisterUsername('');
        setRegisterPassword('');
        
        // 保存登录状态到localStorage
        localStorage.setItem('user', JSON.stringify({ username: registerUsername, isGuest: false }));
      } else {
        setAuthError(result.message || '注册失败');
      }
    } catch (error) {
      console.error('注册异常:', error);
      setAuthError('注册时发生错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 游客登录
  const guestLogin = () => {
    const guestUsername = generateGuestUsername();
    setUser({ username: guestUsername, isGuest: true });
    setShowLoginModal(false);
    
    // 从localStorage加载游客数据
    try {
      const storedTodos = localStorage.getItem(`guest_${guestUsername}_todos`);
      const storedGroups = localStorage.getItem(`guest_${guestUsername}_taskGroups`);
      
      if (storedGroups) {
        const parsedGroups = JSON.parse(storedGroups).map((group: any) => ({
          ...group,
          createTime: new Date(group.createTime)
        }));
        setTaskGroups(parsedGroups);
      }
      
      if (storedTodos) {
        const parsedTodos = JSON.parse(storedTodos).map((todo: any) => ({
          ...todo,
          createTime: new Date(todo.createTime),
          groupId: todo.groupId || 'default'
        }));
        setTodos(parsedTodos);
      }
    } catch (e) {
      console.error('加载游客数据失败:', e);
    }
  };

  // 用户登出
  const logout = () => {
    if (window.confirm('确定要登出吗？')) {
      // 如果是游客，保存数据到localStorage
      if (user?.isGuest) {
        try {
          localStorage.setItem(`guest_${user.username}_todos`, JSON.stringify(todos));
          localStorage.setItem(`guest_${user.username}_taskGroups`, JSON.stringify(taskGroups));
        } catch (e) {
          console.error('保存游客数据失败:', e);
        }
      }
      
      // 清除用户状态
      setUser(null);
      localStorage.removeItem('user');
      
      // 重置应用状态
      const defaultGroup: TaskGroup = {
        id: 'default',
        name: '默认任务组',
        createTime: new Date()
      };
      setTaskGroups([defaultGroup]);
      setTodos([]);
      setCurrentGroupId('default');
    }
  };

  // API存储函数 - 将数据保存到本地服务器或浏览器存储
  const saveToStorage = async (key: string, data: any) => {
    try {
      // 如果是已登录用户，保存到服务器
      if (user && !user.isGuest) {
        console.log(`🟢 保存用户 ${user.username} 的 ${key} 数据到服务器`);
        
        const response = await fetch('/api/saveUserData', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: user.username,
            data: {
              todos: key === 'todos' ? data : todos,
              taskGroups: key === 'taskGroups' ? data : taskGroups
            }
          }),
        });
        
        if (response.ok) {
          const result = await response.json();
          if (result.success) {
            console.log(`✅ 服务器保存 ${key} 成功`);
            return true;
          }
        }
        console.error(`❌ 服务器保存 ${key} 失败`);
        return false;
      }
      // 如果是游客或未登录，保存到localStorage
      else if (user?.isGuest) {
        console.log(`🟡 保存游客 ${user.username} 的 ${key} 数据到浏览器`);
        localStorage.setItem(`guest_${user.username}_${key}`, JSON.stringify(data));
        return true;
      }
    } catch (error) {
      console.error(`❌ 保存数据异常:`, error);
    }
    return false;
  };

  // API加载函数 - 从本地服务器或浏览器存储获取数据
  const loadFromStorage = async (key: string, defaultValue: any = []) => {
    try {
      // 如果是已登录用户，从服务器加载
      if (user && !user.isGuest) {
        console.log(`🔄 从服务器加载用户 ${user.username} 的 ${key} 数据`);
        
        const response = await fetch('/api/userData', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ username: user.username }),
        });
        
        if (response.ok) {
          const result = await response.json();
          if (result.success && result.data) {
            const data = key === 'todos' ? result.data.todos : result.data.taskGroups;
            
            if (Array.isArray(data)) {
              console.log(`✅ 成功加载 ${key} 数据，数量: ${data.length}`);
              return data;
            }
          }
        }
      }
      // 如果是游客，从localStorage加载
      else if (user?.isGuest) {
        console.log(`🔄 从浏览器加载游客 ${user.username} 的 ${key} 数据`);
        const stored = localStorage.getItem(`guest_${user.username}_${key}`);
        if (stored) {
          const parsed = JSON.parse(stored);
          return Array.isArray(parsed) ? parsed : defaultValue;
        }
      }
    } catch (error) {
      console.error(`❌ 加载数据异常:`, error);
    }
    return defaultValue;
  };
  
  // 同步版本的loadFromStorage，用于初始加载
  const loadFromStorageSync = (key: string, defaultValue: any = []) => {
    try {
      // 尝试从localStorage读取用户信息
      if (typeof localStorage !== 'undefined') {
        const userStr = localStorage.getItem('user');
        if (userStr) {
          const savedUser = JSON.parse(userStr);
          if (savedUser.isGuest) {
            // 游客数据
            const stored = localStorage.getItem(`guest_${savedUser.username}_${key}`);
            if (stored) {
              const parsed = JSON.parse(stored);
              return Array.isArray(parsed) ? parsed : defaultValue;
            }
          }
        }
        // 离线数据作为降级方案
        const stored = localStorage.getItem(`offline_${key}`);
        if (stored) {
          const parsed = JSON.parse(stored);
          return Array.isArray(parsed) ? parsed : defaultValue;
        }
      }
    } catch (error) {
      console.error(`❌ 降级加载 ${key} 失败:`, error);
    }
    return defaultValue;
  };

  // 从服务器加载任务和任务组
  useEffect(() => {
    const loadInitialData = async () => {
      try {
        // 检查是否有保存的用户登录状态
        const savedUserStr = localStorage.getItem('user');
        if (savedUserStr) {
          const savedUser = JSON.parse(savedUserStr);
          setUser(savedUser);
          
          // 如果是已登录用户，从服务器加载数据
          if (!savedUser.isGuest) {
            console.log(`🔄 恢复登录状态: ${savedUser.username}`);
            const response = await fetch('/api/userData', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ username: savedUser.username }),
            });
            
            if (response.ok) {
              const result = await response.json();
              if (result.success && result.data) {
                const { todos: userTodos, taskGroups: userGroups } = result.data;
                
                // 处理任务组数据
                if (userGroups && userGroups.length > 0) {
                  try {
                    const parsedGroups = userGroups.map((group: any) => ({
                      ...group,
                      createTime: new Date(group.createTime)
                    }));
                    setTaskGroups(parsedGroups);
                  } catch (e) {
                    console.error('解析用户任务组失败:', e);
                  }
                }
                
                // 处理任务数据
                if (userTodos && userTodos.length > 0) {
                  try {
                    const parsedTodos = userTodos.map((todo: any) => ({
                      ...todo,
                      createTime: new Date(todo.createTime),
                      groupId: todo.groupId || 'default'
                    }));
                    setTodos(parsedTodos);
                  } catch (e) {
                    console.error('解析用户任务失败:', e);
                  }
                }
              }
            }
          } else {
            // 如果是游客，从localStorage加载数据
            console.log(`🔄 恢复游客状态: ${savedUser.username}`);
            try {
              const storedGroups = localStorage.getItem(`guest_${savedUser.username}_taskGroups`);
              const storedTodos = localStorage.getItem(`guest_${savedUser.username}_todos`);
              
              if (storedGroups) {
                const parsedGroups = JSON.parse(storedGroups).map((group: any) => ({
                  ...group,
                  createTime: new Date(group.createTime)
                }));
                setTaskGroups(parsedGroups);
              }
              
              if (storedTodos) {
                const parsedTodos = JSON.parse(storedTodos).map((todo: any) => ({
                  ...todo,
                  createTime: new Date(todo.createTime),
                  groupId: todo.groupId || 'default'
                }));
                setTodos(parsedTodos);
              }
            } catch (e) {
              console.error('加载游客数据失败:', e);
            }
          }
        } else {
          // 如果没有保存的用户状态，显示默认界面
          // 先使用同步的降级方案显示初始界面
          const offlineGroups = loadFromStorageSync('taskGroups');
          const offlineTodos = loadFromStorageSync('todos');
          
          // 显示离线数据（如果有）
          if (offlineGroups.length > 0) {
            try {
              setTaskGroups(offlineGroups.map((group: any) => ({
                ...group,
                createTime: new Date(group.createTime)
              })))
            } catch (e) {
              console.error('Failed to parse offline task groups:', e);
            }
          } else {
            // 创建默认任务组
            const defaultGroup: TaskGroup = {
              id: 'default',
              name: '默认任务组',
              createTime: new Date()
            };
            setTaskGroups([defaultGroup]);
          }
          
          if (offlineTodos.length > 0) {
            try {
              setTodos(offlineTodos.map((todo: any) => ({
                ...todo,
                createTime: new Date(todo.createTime),
                groupId: todo.groupId || 'default'
              })))
            } catch (e) {
              console.error('Failed to parse offline todos:', e);
            }
          }
        }
      } catch (error) {
        console.error('加载初始数据失败:', error);
        // 确保有默认任务组
        const defaultGroup: TaskGroup = {
          id: 'default',
          name: '默认任务组',
          createTime: new Date()
        };
        setTaskGroups([defaultGroup]);
      }
    };
    
    loadInitialData();
  }, []);

  
  // 添加定时器定期从服务器刷新数据（仅对已登录用户有效）
  useEffect(() => {
    // 只有已登录用户才需要定期刷新
    if (!user || user.isGuest) return;
    
    const refreshInterval = setInterval(async () => {
      // 定期重新从服务器加载数据，实现多窗口同步
      console.log('🔄 自动从服务器刷新数据...');
      
      try {
        // 重新加载任务组
        const latestGroups = await loadFromStorage('taskGroups');
        if (latestGroups && JSON.stringify(latestGroups) !== JSON.stringify(taskGroups)) {
          console.log('📊 发现更新的任务组数据，正在更新...');
          try {
            const parsedGroups = latestGroups.map((group: any) => ({
              ...group,
              createTime: new Date(group.createTime)
            }));
            setTaskGroups(parsedGroups);
          } catch (e) {
            console.error('从服务器刷新任务组失败:', e);
          }
        }
        
        // 重新加载任务
        const latestTodos = await loadFromStorage('todos');
        if (latestTodos && JSON.stringify(latestTodos) !== JSON.stringify(todos)) {
          console.log('✅ 发现更新的任务数据，正在更新...');
          try {
            const parsedTodos = latestTodos.map((todo: any) => ({
              ...todo,
              createTime: new Date(todo.createTime),
              groupId: todo.groupId || 'default'
            }));
            setTodos(parsedTodos);
          } catch (e) {
            console.error('从服务器刷新任务失败:', e);
          }
        }
      } catch (error) {
        console.error('自动刷新数据异常:', error);
      }
    }, 5000); // 每5秒刷新一次
    
    return () => clearInterval(refreshInterval);
  }, [todos, taskGroups, user]);
  
  // 清空所有服务器数据
  const clearAllData = async () => {
    if (window.confirm('确定要清空所有任务数据吗？此操作不可撤销。')) {
      console.log('🗑️  正在清空服务器上的所有数据...');
      
      try {
        // 调用服务器API清空数据
        const response = await fetch('/api/allData', {
          method: 'DELETE',
        });
        
        if (response.ok) {
          console.log('✅ 服务器数据清空成功');
          
          // 重置应用状态
          const defaultGroup: TaskGroup = {
            id: 'default',
            name: '默认任务组',
            createTime: new Date()
          };
          setTaskGroups([defaultGroup]);
          setTodos([]);
          setCurrentGroupId('default');
          
          console.log('✅ 应用状态已重置');
        } else {
          console.error('❌ 服务器数据清空失败');
          // 降级处理：至少清空前端状态
          const defaultGroup: TaskGroup = {
            id: 'default',
            name: '默认任务组',
            createTime: new Date()
          };
          setTaskGroups([defaultGroup]);
          setTodos([]);
          setCurrentGroupId('default');
        }
      } catch (error) {
        console.error('❌ 清空数据异常:', error);
        // 降级处理：至少清空前端状态
        const defaultGroup: TaskGroup = {
          id: 'default',
          name: '默认任务组',
          createTime: new Date()
        };
        setTaskGroups([defaultGroup]);
        setTodos([]);
        setCurrentGroupId('default');
      }
    }
  };

  // 保存任务组数据
  useEffect(() => {
    if (taskGroups.length > 0) {
      // 使用异步函数包装异步保存操作
      const saveTaskGroups = async () => {
        try {
          const success = await saveToStorage('taskGroups', taskGroups);
          if (!success) {
            console.warn('任务组数据保存失败，尝试降级保存...');
            // 降级方案：保存离线数据
            if (typeof localStorage !== 'undefined') {
              localStorage.setItem('offline_taskGroups', JSON.stringify(taskGroups));
            }
          }
        } catch (error) {
          console.error('保存任务组数据异常:', error);
          // 降级保存
          if (typeof localStorage !== 'undefined') {
            localStorage.setItem('offline_taskGroups', JSON.stringify(taskGroups));
          }
        }
      };
      saveTaskGroups();
    }
  }, [taskGroups, user])

  // 保存任务数据
  useEffect(() => {
    // 使用异步函数包装异步保存操作
    const saveTodos = async () => {
      try {
        const success = await saveToStorage('todos', todos);
        if (!success) {
          console.warn('任务数据保存失败，尝试降级保存...');
          // 降级方案：保存离线数据
          if (typeof localStorage !== 'undefined') {
            localStorage.setItem('offline_todos', JSON.stringify(todos));
          }
        }
      } catch (error) {
        console.error('保存任务数据异常:', error);
        // 降级保存
        if (typeof localStorage !== 'undefined') {
          localStorage.setItem('offline_todos', JSON.stringify(todos));
        }
      }
    };
    saveTodos();
  }, [todos, user])

  // 添加新任务
  const addTodo = () => {
    if (inputText.trim()) {
      // 添加新任务时，如果当前是"所有任务"视图，则默认添加到默认任务组
      const targetGroupId = currentGroupId === 'all' ? 'default' : currentGroupId
      // 使用正确的时间格式，确保不会有时区问题
      const now = new Date();
      const newTodo: Todo = {
        id: Date.now().toString(),
        text: inputText.trim(),
        completed: false,
        createTime: now,
        groupId: targetGroupId,
        status: 'pending'
      }
      const updatedTodos = [...todos, newTodo];
      setTodos(updatedTodos);
      console.log('New task added:', newTodo);
      console.log('Current tasks count:', updatedTodos.length);
      setInputText('')
    }
  }
  
  // 添加带详细信息的新任务
  const addTodoWithDetails = () => {
    if (inputText.trim()) {
      // 添加新任务时，如果当前是"所有任务"视图，则默认添加到默认任务组
      const targetGroupId = currentGroupId === 'all' ? 'default' : currentGroupId
      const now = new Date();
      const newTodo: Todo = {
        id: Date.now().toString(),
        text: inputText.trim(),
        completed: false,
        createTime: now,
        groupId: targetGroupId,
        status: 'pending',
        assignee: taskAssignee || undefined,
        dueTime: taskDueTime ? new Date(taskDueTime) : undefined,
        description: taskDescription || undefined
      }
      const updatedTodos = [...todos, newTodo];
      setTodos(updatedTodos);
      console.log('New task with details added:', newTodo);
      console.log('Current tasks count:', updatedTodos.length);
      
      // 重置表单
      setInputText('')
      setTaskAssignee('')
      setTaskDueTime('')
      setTaskDescription('')
      setShowAddTaskModal(false)
    }
  }
  
  // 切换任务状态
  const changeTaskStatus = (id: string, newStatus: TaskStatus) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, status: newStatus } : todo
    ));
  }
  
  // 更新任务责任人
  const updateTaskAssignee = (id: string, assignee: string) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, assignee: assignee.trim() || undefined } : todo
    ));
  }
  
  // 更新任务预期完成时间
  const updateTaskDueTime = (id: string, dueTime: string) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, dueTime: dueTime ? new Date(dueTime) : undefined } : todo
    ));
  }
  
  // 全选任务
  const selectAllTodos = () => {
    const filteredTodoIds = filteredTodos.map(todo => todo.id);
    setSelectedTodoIds(filteredTodoIds);
  }
  
  // 取消选择所有任务
  const clearSelection = () => {
    setSelectedTodoIds([]);
  }
  
  // 切换单个任务选择状态
  const toggleTodoSelection = (id: string) => {
    setSelectedTodoIds(prev => 
      prev.includes(id) 
        ? prev.filter(todoId => todoId !== id)
        : [...prev, id]
    );
  }
  
  // 完成选中的任务
  const completeSelectedTodos = () => {
    setTodos(todos.map(todo => 
      selectedTodoIds.includes(todo.id) 
        ? { ...todo, completed: true }
        : todo
    ));
    setSelectedTodoIds([]);
  }
  
  // 删除选中的任务
  const deleteSelectedTodos = () => {
    setTodos(todos.filter(todo => !selectedTodoIds.includes(todo.id)));
    setSelectedTodoIds([]);
  }
  
  // 获取所有责任人列表
  const allAssignees = Array.from(new Set(todos.map(todo => todo.assignee).filter(Boolean))).sort();
  
  // 切换时间排序方向
  const toggleSortDirection = () => {
    setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
  }

  // 添加新任务组
  const addTaskGroup = () => {
    const trimmedGroupName = newGroupName.trim()
    if (trimmedGroupName) {
      // 检查是否已存在同名任务组
      const isDuplicate = taskGroups.some(group => 
        group.name.toLowerCase() === trimmedGroupName.toLowerCase()
      )
      
      // 检查是否为默认任务组名称
      const isDefaultName = trimmedGroupName.toLowerCase() === '默认任务组'
      
      if (isDuplicate) {
        alert('任务组名称已存在，请使用其他名称！')
        return
      }
      
      if (isDefaultName) {
        alert('不能创建名为"默认任务组"的任务组！')
        return
      }
      
      const newGroup: TaskGroup = {
        id: Date.now().toString(),
        name: trimmedGroupName,
        createTime: new Date()
      }
      setTaskGroups([...taskGroups, newGroup])
      setCurrentGroupId(newGroup.id)
      setNewGroupName('')
      setShowAddGroupModal(false)
    }
  }

  // 删除任务组
  const deleteTaskGroup = (groupId: string) => {
    if (groupId === 'default') return // 不允许删除默认任务组
    
    // 将该组的任务移动到默认组
    setTodos(todos.map(todo => 
      todo.groupId === groupId ? { ...todo, groupId: 'default' } : todo
    ))
    
    // 删除任务组
    setTaskGroups(taskGroups.filter(group => group.id !== groupId))
    
    // 如果当前选中的是被删除的组，切换到默认组
    if (currentGroupId === groupId) {
      setCurrentGroupId('default')
    }
  }

  // 处理回车键添加任务
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      addTodo()
    }
  }

  // 切换任务完成状态
  const toggleTodo = (id: string) => {
    setTodos(todos.map(todo => 
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ))
  }

  // 删除任务
  const deleteTodo = (id: string) => {
    setTodos(todos.filter(todo => todo.id !== id))
  }

  // 清除所有已完成任务
  const clearCompleted = () => {
    setTodos(todos.filter(todo => !todo.completed))
  }

  // 根据当前任务组和过滤器获取任务
  const filteredTodos = todos
    .filter(todo => {
      // 如果是"所有任务"，跳过任务组过滤
      if (currentGroupId !== 'all' && todo.groupId !== currentGroupId) return false
      // 按完成状态过滤
      if (filter === 'active') return !todo.completed
      if (filter === 'completed') return todo.completed
      // 按任务状态过滤
      if (statusFilter !== 'all' && todo.status !== statusFilter) return false
      // 按责任人过滤
      if (assigneeFilter && todo.assignee !== assigneeFilter) return false
      return true
    })
    .sort((a, b) => {
      // 按创建时间排序
      const dateA = new Date(a.createTime).getTime();
      const dateB = new Date(b.createTime).getTime();
      return sortDirection === 'asc' ? dateA - dateB : dateB - dateA;
    })

  // 计算当前任务组中未完成任务数量
  const activeCount = todos.filter(todo => 
    (currentGroupId === 'all' || todo.groupId === currentGroupId) && !todo.completed
  ).length

  // 获取当前任务组名称
  const currentGroupName = currentGroupId === 'all' 
    ? '所有任务'
    : (taskGroups.find(group => group.id === currentGroupId)?.name || '默认任务组')

  // 格式化创建时间
  const formatTime = (date: Date) => {
    // 确保date是Date对象
    const targetDate = typeof date === 'string' ? new Date(date) : date;
    if (isNaN(targetDate.getTime())) {
      return '时间未知';
    }
    
    const now = new Date();
    const diff = now.getTime() - targetDate.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(hours / 24);
    
    if (hours < 1) return '刚刚';
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    
    // 使用更详细的日期格式
    return targetDate.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  }

  return (
    <div className="feishu-app">
      {/* 移动端菜单按钮 */}
      <button 
        className="mobile-menu-btn" 
        onClick={() => setShowSidebar(true)}
        aria-label="打开侧边栏"
      >
        ≡
      </button>
      
      {/* 侧边栏 */}
      <aside className={`sidebar ${showSidebar ? 'open' : 'closed'}`}>
        <div className="sidebar-header">
          <div className="logo">
            <span className="logo-icon">📝</span>
            <span className="logo-text">待办事项</span>
          </div>
          <button 
            className="toggle-sidebar" 
            onClick={() => setShowSidebar(!showSidebar)}
            aria-label={showSidebar ? '收起侧边栏' : '展开侧边栏'}
          >
            {showSidebar ? '‹' : '›'}
          </button>
        </div>
        
        <nav className="sidebar-nav">
          <div className="nav-section">
            <div className="section-title">任务组</div>
            {/* 所有任务特殊选项 */}
            <div 
              className={`nav-item ${currentGroupId === 'all' ? 'active' : ''}`}
              onClick={() => setCurrentGroupId('all')}
            >
              <span className="nav-icon">📝</span>
              <span className="nav-text">所有任务</span>
            </div>
            
            {taskGroups.map(group => (
              <div 
                key={group.id} 
                className={`nav-item ${currentGroupId === group.id ? 'active' : ''}`}
                onClick={() => setCurrentGroupId(group.id)}
              >
                <span className="nav-icon">📋</span>
                <span className="nav-text">{group.name}</span>
                {group.id !== 'default' && (
                  <button 
                    className="delete-group-btn"
                    onClick={(e) => {
                      e.stopPropagation()
                      deleteTaskGroup(group.id)
                    }}
                    aria-label={`删除任务组 ${group.name}`}
                  >
                    ×
                  </button>
                )}
              </div>
            ))}
            <div 
              className="nav-item add-group-item"
              onClick={() => setShowAddGroupModal(true)}
            >
              <span className="nav-icon">+</span>
              <span className="nav-text">新建任务组</span>
            </div>
          </div>
          
          <div className="nav-section">
            <div className="section-title">功能</div>
            <div className="nav-item" onClick={() => console.log('我的任务')}>
              <span className="nav-icon">🏠</span>
              <span className="nav-text">我的任务</span>
            </div>
            <div className="nav-item" onClick={() => console.log('统计报表')}>
              <span className="nav-icon">📊</span>
              <span className="nav-text">统计报表</span>
            </div>
          </div>
          
          <div className="nav-section">
            <div className="section-title">快捷筛选</div>
            <div className="nav-item" onClick={() => console.log('今日待办')}>
              <span className="nav-icon">⏰</span>
              <span className="nav-text">今日待办</span>
            </div>
            <div className="nav-item" onClick={() => console.log('重要任务')}>
              <span className="nav-icon">🔥</span>
              <span className="nav-text">重要任务</span>
            </div>
          </div>
          
          {/* 用户信息区域 - 放在侧边栏底部 */}
          <div className="nav-section user-section">
            <div className="section-title">用户</div>
            {user ? (
              <div className="user-info-container">
                <div className="user-info">
                  <span className="nav-icon">👤</span>
                  <span className="nav-text">
                    {user.username}{user.isGuest ? ' (游客)' : ''}
                  </span>
                </div>
                {user.isGuest ? (
                  <div className="nav-item" onClick={() => setShowRegisterModal(true)}>
                    <span className="nav-icon">📝</span>
                    <span className="nav-text">注册</span>
                  </div>
                ) : (
                  <>
                    <div className="nav-item">
                      <span className="nav-icon">⚙️</span>
                      <span className="nav-text">用户中心</span>
                    </div>
                    <div className="nav-item logout-item" onClick={logout}>
                      <span className="nav-icon">🚪</span>
                      <span className="nav-text">登出</span>
                    </div>
                  </>
                )}
              </div>
            ) : (
              <div className="nav-item" onClick={() => setShowLoginModal(true)}>
                <span className="nav-icon">🔑</span>
                <span className="nav-text">登录/注册</span>
              </div>
            )}
          </div>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="main-content">
        {/* 内容卡片 - 直接展示任务内容 */}
        <div className="content-card">
          {/* 添加任务区域 */}
          <div className="add-task-section">
            <div className={`todo-input-wrapper ${isInputFocused ? 'focused' : ''}`}>
              <input
                type="text"
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                onKeyPress={handleKeyPress}
                onFocus={() => setIsInputFocused(true)}
                onBlur={() => setIsInputFocused(false)}
                placeholder={currentGroupId === 'all' 
                  ? '添加新任务...'
                  : `在「${currentGroupName}」中添加新任务...`}
                className="todo-input"
              />
              <button 
                onClick={() => setShowAddTaskModal(true)} 
                className="add-button"
                aria-label="添加任务"
              >
                <span className="add-icon">+</span>
              </button>
            </div>
          </div>

          {/* 控制栏 - 重新实现为第一行筛选和操作按钮 */}
          <div className="todo-controls">
            <div className="control-row">
              {/* 选择下拉菜单 - 点击展开，移开收起 */}
              <div className="filter-dropdown" onMouseLeave={() => setShowSelectionOptions(false)}>
                <button 
                  onClick={() => setShowSelectionOptions(!showSelectionOptions)}
                  className="dropdown-button"
                >
                  选择
                </button>
                {showSelectionOptions && (
                  <div className="dropdown-menu">
                    <div className="dropdown-item" onClick={() => {
                      selectAllTodos();
                      setShowSelectionOptions(false);
                    }}>
                      全选
                    </div>
                    <div className="dropdown-item" onClick={() => {
                      clearSelection();
                      setShowSelectionOptions(false);
                    }}>
                      取消
                    </div>
                    <div className="dropdown-item" onClick={() => {
                      setShowSelectionOptions(false);
                      // 多选模式可以在这里添加额外逻辑
                    }}>
                      多选
                    </div>
                  </div>
                )}
              </div>
              
              {/* 状态筛选下拉菜单 - 点击展开，移开收起 */}
              <div className="filter-dropdown" onMouseLeave={() => setShowStatusDropdown(false)}>
                <button 
                  className={`dropdown-button ${statusFilter !== 'all' ? 'active' : ''}`}
                  onClick={() => setShowStatusDropdown(!showStatusDropdown)}
                >
                  状态
                </button>
                {showStatusDropdown && (
                  <div className="dropdown-menu">
                    <div 
                        className={`dropdown-item ${statusFilter === 'all' ? 'active' : ''}`}
                        onClick={() => setStatusFilter('all')}
                      >
                        全部
                      </div>
                      <div 
                        className={`dropdown-item ${statusFilter === 'pending' ? 'active' : ''}`}
                        onClick={() => setStatusFilter('pending')}
                      >
                        未开始
                      </div>
                      <div 
                        className={`dropdown-item ${statusFilter === 'inProgress' ? 'active' : ''}`}
                        onClick={() => setStatusFilter('inProgress')}
                      >
                        进行中
                      </div>
                      <div 
                        className={`dropdown-item ${statusFilter === 'completed' ? 'active' : ''}`}
                        onClick={() => setStatusFilter('completed')}
                      >
                        已完成
                      </div>
                      <div 
                        className={`dropdown-item ${statusFilter === 'paused' ? 'active' : ''}`}
                        onClick={() => setStatusFilter('paused')}
                      >
                        暂停
                      </div>
                  </div>
                )}
              </div>
              
              {/* 创建时间排序 */}
              <button 
                onClick={toggleSortDirection}
                className={`sort-button ${sortDirection === 'desc' ? 'desc' : 'asc'}`}
              >
                创建时间 {sortDirection === 'desc' ? '↓' : '↑'}
              </button>
              
              {/* 责任人筛选 */}
              <select 
                value={assigneeFilter}
                onChange={(e) => setAssigneeFilter(e.target.value)}
                className="assignee-filter"
              >
                <option value="">所有责任人</option>
                {allAssignees.map(assignee => (
                  <option key={assignee} value={assignee}>
                    {assignee}
                  </option>
                ))}
              </select>
              
              {/* 完成状态筛选按钮 */}
              <div className="status-filter-buttons">
                <button 
                  onClick={() => setFilter('all')}
                  className={`filter-btn ${filter === 'all' ? 'active' : ''}`}
                >
                  全部
                </button>
                <button 
                  onClick={() => setFilter('active')}
                  className={`filter-btn ${filter === 'active' ? 'active' : ''}`}
                >
                  未完成
                </button>
                <button 
                  onClick={() => setFilter('completed')}
                  className={`filter-btn ${filter === 'completed' ? 'active' : ''}`}
                >
                  已完成
                </button>
              </div>
              
              {/* 操作按钮 - 当选中任务时显示完成和清除按钮 */}
              <div className="selected-actions">
                {selectedTodoIds.length > 0 && (
                  <>
                    <button 
                      onClick={completeSelectedTodos} 
                      className="complete-selected-button"
                    >
                      完成
                    </button>
                    <button 
                      onClick={deleteSelectedTodos} 
                      className="delete-selected-button"
                    >
                      清除
                    </button>
                  </>
                )}
                <button 
                  onClick={clearAllData} 
                  className="clear-all-button"
                  title="清空所有数据（不可撤销）"
                >
                  清空数据
                </button>
              </div>
            </div>
          </div>

          {/* 任务列表 - 表格形式 */}
          <div className="task-list-section">
            <div className="section-header">
              <h2 className="section-title">{currentGroupName}</h2>
              <span className="task-count">{activeCount} 个待办</span>
            </div>
            
            <div className="todo-list">
              {filteredTodos.length === 0 ? (
                <div className="empty-state">
                  <div className="empty-icon">📭</div>
                  <div className="empty-text">暂无任务</div>
                  <div className="empty-hint">添加一个任务开始吧！</div>
                </div>
              ) : (
                <table className="todo-table">
                  <thead>
                    <tr>
                      <th className="task-title-col">任务名称</th>
                      <th className="task-status-col">状态</th>
                      <th className="task-assignee-col">责任人</th>
                      <th className="task-due-col">预期完成时间</th>
                      <th className="task-create-col">创建时间</th>
                      <th className="task-actions-col">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredTodos.map(todo => (
                      <tr 
                        key={todo.id} 
                        className={`todo-item ${todo.completed ? 'completed' : ''}`}
                      >
                        
                        <td className="task-title-col">
                          <div>
                            <span className={`todo-text ${todo.completed ? 'completed' : ''}`}>
                              {todo.text}
                            </span>
                            {todo.description && (
                              <div className="task-description">{todo.description}</div>
                            )}
                          </div>
                        </td>
                        <td className="task-status-col">
                    <div className="status-select-wrapper">
                      <select 
                        className={`task-status-select status-${todo.status}`}
                        value={todo.status}
                        onChange={(e) => changeTaskStatus(todo.id, e.target.value as TaskStatus)}
                      >
                        <option value="pending">未开始</option>
                        <option value="inProgress">进行中</option>
                        <option value="completed">已完成</option>
                        <option value="paused">暂停</option>
                      </select>
                    </div>
                  </td>
                        <td className="task-assignee-col">
                  <input 
                    type="text"
                    className="assignee-input"
                    value={todo.assignee || ''}
                    onChange={(e) => updateTaskAssignee(todo.id, e.target.value)}
                    placeholder="输入责任人"
                  />
                </td>
                <td className="task-due-col">
                  <input 
                    type="date"
                    className="due-time-input"
                    value={todo.dueTime ? new Date(todo.dueTime).toISOString().split('T')[0] : ''}
                    onChange={(e) => updateTaskDueTime(todo.id, e.target.value)}
                  />
                </td>
                        <td className="task-create-col">
                          {formatTime(todo.createTime)}
                        </td>
                        <td className="task-actions-col">
                          <button 
                            onClick={() => toggleTodoSelection(todo.id)}
                            className={`select-button ${selectedTodoIds.includes(todo.id) ? 'selected' : ''}`}
                            aria-label={selectedTodoIds.includes(todo.id) ? '取消选择' : '选择任务'}
                          >
                            {selectedTodoIds.includes(todo.id) && <span className="select-icon">✓</span>}
                          </button>
                          <button 
                            onClick={() => deleteTodo(todo.id)}
                            className="delete-button"
                            aria-label="删除任务"
                          >
                            <span className="delete-icon">×</span>
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      </main>

      {/* 新建任务组模态框 */}
      {showAddGroupModal && (
        <div className="modal-overlay" onClick={() => setShowAddGroupModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <h3 className="modal-title">新建任务组</h3>
            <input
              type="text"
              value={newGroupName}
              onChange={(e) => setNewGroupName(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter') {
                  addTaskGroup()
                }
              }}
              placeholder="输入任务组名称"
              className="modal-input"
              autoFocus
            />
            <div className="modal-actions">
              <button 
                className="modal-button cancel-button"
                onClick={() => {
                  setShowAddGroupModal(false)
                  setNewGroupName('')
                }}
              >
                取消
              </button>
              <button 
                className="modal-button confirm-button"
                onClick={addTaskGroup}
                disabled={!newGroupName.trim()}
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 添加任务模态框 */}
      {showAddTaskModal && (
        <div className="modal-overlay" onClick={() => setShowAddTaskModal(false)}>
          <div className="modal-content add-task-modal" onClick={(e) => e.stopPropagation()}>
            <h3 className="modal-title">添加任务</h3>
            
            <div className="form-group">
              <label htmlFor="task-text">任务名称 <span className="required">*</span></label>
              <input
                id="task-text"
                type="text"
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                placeholder="请输入任务名称"
                className="modal-input"
                autoFocus
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="task-assignee">责任人</label>
              <input
                id="task-assignee"
                type="text"
                value={taskAssignee}
                onChange={(e) => setTaskAssignee(e.target.value)}
                placeholder="请输入责任人（可选）"
                className="modal-input"
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="task-due-time">预期完成时间</label>
              <input
                id="task-due-time"
                type="date"
                value={taskDueTime}
                onChange={(e) => setTaskDueTime(e.target.value)}
                className="modal-input"
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="task-description">详细信息</label>
              <textarea
                id="task-description"
                value={taskDescription}
                onChange={(e) => setTaskDescription(e.target.value)}
                placeholder="请输入详细信息（可选）"
                className="modal-input modal-textarea"
                rows={4}
              />
            </div>
            
            <div className="modal-actions">
              <button 
                className="modal-button cancel-button"
                onClick={() => {
                  setShowAddTaskModal(false)
                  setInputText('')
                  setTaskAssignee('')
                  setTaskDueTime('')
                  setTaskDescription('')
                }}
              >
                取消
              </button>
              <button 
                className="modal-button confirm-button"
                onClick={addTodoWithDetails}
                disabled={!inputText.trim()}
              >
                添加
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 登录模态框 */}
      {showLoginModal && (
        <div className="modal-overlay" onClick={() => setShowLoginModal(false)}>
          <div className="modal-content login-modal" onClick={(e) => e.stopPropagation()}>
            <h3 className="modal-title">登录</h3>
            {authError && <div className="auth-error">{authError}</div>}
            
            <div className="form-group">
              <label htmlFor="login-username">用户名</label>
              <input
                id="login-username"
                type="text"
                value={loginUsername}
                onChange={(e) => setLoginUsername(e.target.value)}
                placeholder="请输入用户名"
                className="modal-input"
                autoFocus
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="login-password">密码</label>
              <input
                id="login-password"
                type="password"
                value={loginPassword}
                onChange={(e) => setLoginPassword(e.target.value)}
                placeholder="请输入密码"
                className="modal-input"
              />
            </div>
            
            <div className="modal-actions">
              <button 
                className="modal-button cancel-button"
                onClick={() => {
                  setShowLoginModal(false)
                  setLoginUsername('')
                  setLoginPassword('')
                  setAuthError('')
                }}
              >
                取消
              </button>
              <button 
                className="modal-button confirm-button"
                onClick={login}
                disabled={!loginUsername.trim() || !loginPassword.trim() || isLoading}
              >
                {isLoading ? '登录中...' : '登录'}
              </button>
            </div>
            
            <div className="auth-divider">或</div>
            
            <div className="modal-actions">
              <button 
                className="modal-button guest-button"
                onClick={guestLogin}
                disabled={isLoading}
              >
                游客登录
              </button>
            </div>
            
            <div className="switch-auth-mode">
              还没有账号？{' '}
              <button 
                className="switch-button"
                onClick={() => {
                  setShowLoginModal(false)
                  setShowRegisterModal(true)
                  setAuthError('')
                }}
              >
                立即注册
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 注册模态框 */}
      {showRegisterModal && (
        <div className="modal-overlay" onClick={() => setShowRegisterModal(false)}>
          <div className="modal-content register-modal" onClick={(e) => e.stopPropagation()}>
            <h3 className="modal-title">{user?.isGuest ? '注册账号并保存数据' : '注册'}</h3>
            {authError && <div className="auth-error">{authError}</div>}
            
            {user?.isGuest && (
              <div className="auth-info">
                <p>注册后，您当前的{user.username}（游客）数据将被保存到您的新账号中。</p>
              </div>
            )}
            
            <div className="form-group">
              <label htmlFor="register-username">用户名</label>
              <input
                id="register-username"
                type="text"
                value={registerUsername}
                onChange={(e) => setRegisterUsername(e.target.value)}
                placeholder="请设置用户名"
                className="modal-input"
                autoFocus
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="register-password">密码</label>
              <input
                id="register-password"
                type="password"
                value={registerPassword}
                onChange={(e) => setRegisterPassword(e.target.value)}
                placeholder="请设置密码"
                className="modal-input"
              />
            </div>
            
            <div className="modal-actions">
              <button 
                className="modal-button cancel-button"
                onClick={() => {
                  setShowRegisterModal(false)
                  setRegisterUsername('')
                  setRegisterPassword('')
                  setAuthError('')
                }}
              >
                取消
              </button>
              <button 
                className="modal-button confirm-button"
                onClick={register}
                disabled={!registerUsername.trim() || !registerPassword.trim() || isLoading}
              >
                {isLoading ? '注册中...' : '注册'}
              </button>
            </div>
            
            <div className="switch-auth-mode">
              已有账号？{' '}
              <button 
                className="switch-button"
                onClick={() => {
                  setShowRegisterModal(false)
                  setShowLoginModal(true)
                  setAuthError('')
                }}
              >
                返回登录
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default App